package csloader.loaders
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	
	import csloader.events.EventDelegate;
	import csloader.events.ExtraEvent;
	import csloader.requests.QueueRequest;
	import csloader.util.KeyValuePair;
	import csloader.util.RequestMethod;
	
	public class DisplayObjectLoaderBase extends QueueRequest implements ILoader
	{
		//内部参数
		protected var contentLoader:Loader;
		protected var contentCompleteDelegate:Function;
		protected var contentIoErrorDelegate:Function;	
		
		public function DisplayObjectLoaderBase(callback:Function)
		{
			super(callback);
			
			if(String(this)=="[object DisplayObjectLoaderBase]")
				throw new Error("无法创建抽象类“csloader.loaders.DisplayObjectLoaderBase”的实例。");
		}
		
		/**
		 * 将ByteArray加载到可视对象中
		 * @param url
		 * @param response
		 * 
		 */
		override public function sendResponse(url:String, response:*=null) : void
		{
			contentLoader = new Loader();
			contentCompleteDelegate = EventDelegate.create(contentCompleteHandler, url);
			contentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, contentCompleteDelegate);
			contentIoErrorDelegate = EventDelegate.create(contentIoErrorHandler, url);
			contentLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, contentIoErrorDelegate);
			try {
				contentLoader.loadBytes(response);
			} catch (e:Error) {
				sendContentResponse(url);
				contentDispose();
			}
		}
		
		protected function contentCompleteHandler(e:Event, url:String):void {
			var loaderinfo:LoaderInfo = LoaderInfo(e.target);			
			var response:DisplayObject = null;
			//var response:Bitmap = new Bitmap(Bitmap(loaderinfo.content).bitmapData.clone());
			sendContentResponse(url, response);
			contentDispose();
		}
		
		protected function contentIoErrorHandler(e:IOErrorEvent, url:String):void {
			sendContentResponse(url);
			contentDispose();
		}
		
		protected function sendContentResponse(url:String, response:*=null):void
		{
			//数据正常返回
			callback.apply(null, [new ExtraEvent(Event.COMPLETE, url, response)]);
		}
		
		protected function contentDispose():void
		{
			contentLoader.unloadAndStop();
			
			if(contentLoader.contentLoaderInfo.hasEventListener(Event.COMPLETE))
				contentLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE,contentCompleteDelegate);
			if(contentLoader.contentLoaderInfo.hasEventListener(IOErrorEvent.IO_ERROR))
				contentLoader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,contentIoErrorDelegate);		
		}
		
		public function call(url:String, parms:KeyValuePair=null, requestMethod:String=RequestMethod.Get, ...args):void
		{
			sendRequest(getRequest(url, parms, requestMethod, args));
		}
	}
}